package org.csu.demo.nio_chat.controller;

import org.csu.demo.nio_chat.clientwithWeb.ChatClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class ChatController {
    private ChatClient chatClient = new ChatClient();

    @GetMapping("/chat")
    public String showChatPage(Model model) {
        List<String> messages = chatClient.getMessages();
        model.addAttribute("messages", messages);
        System.out.println("getMessages: " + messages);
        return "chat";
    }

    @PostMapping("/chat")
    public String sendMessage(@RequestParam String name, @RequestParam String msg, Model model) {
        chatClient.sendMessage(name, msg);
        // 手动刷新消息列表
        List<String> messages = chatClient.getMessages();System.out.println("更新后的消息列表:"+messages);
        model.addAttribute("messages", messages);
        System.out.println("sendMessage: " + name + ": " + msg);
        return "chat";
    }
}